package com.jh.readme.common.fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.jh.readme.R;
import com.jh.readme.iu.fragment.music.MusicFragment;
import com.jh.readme.iu.fragment.news.NewsFragmente;
import com.jh.readme.iu.fragment.picturelist.PictureListFragment;
import com.jh.readme.iu.fragment.video.VideoFragment;
import com.jh.tools.base.BaseFragment;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by niejiahuan on 2016/3/12.
 * Fragment切换管理类
 */
public class MainTabFragmentManager {
    private static FragmentManager mFragmentManager;
    private Map<String,BaseFragment> AppFragmentS;
    private static MainTabFragmentManager mMainTabFragmentManager;
    private BaseFragment cAppFragment;
    public static MainTabFragmentManager getInstance(){
        return mMainTabFragmentManager==null?new MainTabFragmentManager():mMainTabFragmentManager;
    }
    public MainTabFragmentManager(FragmentManager fragmentManager){
        mFragmentManager=fragmentManager;
        initAppFragments();
    }
    public MainTabFragmentManager(){
        initAppFragments();
    }

    /**
     * 初始化管理
     * @param fragmentManager
     */
    public void setmFragmentManager(FragmentManager fragmentManager){
        mFragmentManager=fragmentManager;
    }
    public void initAppFragments(){
        if (null==AppFragmentS){
            AppFragmentS=new HashMap<>();
            AppFragmentS.put(NewsFragmente.class.getName(),new NewsFragmente());
            AppFragmentS.put(MusicFragment.class.getName(),new MusicFragment());
            AppFragmentS.put(PictureListFragment.class.getName(),new PictureListFragment());
            AppFragmentS.put(VideoFragment.class.getName(),new VideoFragment());
        }

    }
    /**
     * 切换Tab
     * @param tagName
     */
    public void switchTab(String tagName){
        if (null!=mFragmentManager&&null!=AppFragmentS){
            FragmentTransaction fragmentTransaction= mFragmentManager.beginTransaction();
            BaseFragment AppFragment= AppFragmentS.get(tagName);
            if (!AppFragment.isAdded()){
                fragmentTransaction.add(R.id.home_content,AppFragment).show(AppFragment);
            }else{
                fragmentTransaction.hide(cAppFragment).show(AppFragment);
            }
            fragmentTransaction.commitAllowingStateLoss();
        }
    }
    public void clear(){
        mFragmentManager=null;
    }
}
